package org.yzh.protocol.basics;

import io.github.yezhihao.netmc.core.model.Message;
import io.github.yezhihao.protostar.DataType;
import io.github.yezhihao.protostar.Schema;
import io.github.yezhihao.protostar.annotation.Field;
import io.github.yezhihao.protostar.util.ToStringBuilder;
import io.netty.buffer.ByteBuf;

import java.nio.charset.StandardCharsets;

/**
 * @author yezhihao
 * @home https://gitee.com/yezhihao/jt808-server
 */
public class GTMessage implements Message, Schema<GTMessage> {

    @Field(index = 0, type = DataType.BYTE, desc = "命令标识")
    protected int messageId;
    @Field(index = 1, type = DataType.BYTE, desc = "应答标志")
    protected int statusCode;
    @Field(index = 2, type = DataType.STRING, length = 17, desc = "唯一识别码")
    protected String clientId;
    @Field(index = 19, type = DataType.BYTE, desc = "加密方式")
    protected int encryption;

    @Override
    public int getMessageId() {
        return messageId;
    }

    @Override
    public String getMessageName() {
        return null;
    }

    @Override
    public int getSerialNo() {
        return 0;
    }

    public void setMessageId(int messageId) {
        this.messageId = messageId;
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    @Override
    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public int getEncryption() {
        return encryption;
    }

    public void setEncryption(int encryption) {
        this.encryption = encryption;
    }


    @Override
    public GTMessage readFrom(ByteBuf byteBuf) {
        GTMessage result = new GTMessage();
        result.messageId = byteBuf.readUnsignedByte();
        result.statusCode = byteBuf.readUnsignedByte();
        result.clientId = byteBuf.readCharSequence(17, StandardCharsets.US_ASCII).toString();
        result.encryption = byteBuf.readUnsignedByte();
        return result;
    }

    @Override
    public void writeTo(ByteBuf byteBuf, GTMessage gtMessage) {

    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder(768);
        sb.append(MessageId.get(messageId));
        sb.append('[');
        sb.append("cid=").append(clientId);
        sb.append(",msg=").append(messageId);
        sb.append(']');
        sb.append(',');
        String result = ToStringBuilder.toString(sb, this, false, "messageId", "clientId", "protocolVersion", "serialNo", "properties", "packageTotal", "packageNo");
        return result;
    }

}